//package com.yunxin.admin.system.api.system;
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.util.ObjUtil;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.yunxin.admin.system.application.UserApplicationService;
//import com.yunxin.admin.system.application.UserQueryService;
//import com.yunxin.admin.system.application.command.AddUserMerchantCommand;
//import com.yunxin.admin.system.application.command.UpdateUserMerchantCommand;
//import com.yunxin.admin.system.application.command.UserMerchantPageCommand;
//import com.yunxin.admin.system.application.dto.AdminMerchantUserAccountInfoDTO;
//import com.yunxin.admin.system.application.dto.UpdateUserDetailDTO;
//import com.yunxin.admin.system.application.dto.UserDetailDTO;
//import com.yunxin.admin.system.domain.model.user.UserMerchantRepository;
//import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
//import com.yunxin.admin.system.infra.common.constant.SystemConstants;
//import com.yunxin.admin.system.infra.common.enums.AdminResultCode;
//import com.yunxin.admin.system.infra.framework.resubmit.Resubmit;
//import com.yunxin.admin.system.infra.framework.security.util.SecurityUtils;
//import com.yunxin.admin.system.infra.framework.syslog.AutoLog;
//import com.yunxin.admin.system.infra.persistence.entity.SysRoleDO;
//import com.yunxin.admin.system.infra.persistence.entity.query.result.UserMerchantInfoResult;
//import com.yunxin.common.exception.BusinessException;
//import com.yunxin.common.result.PageResult;
//import com.yunxin.common.result.Result;
//import com.yunxin.core.application.dto.merchant.MerchantUserAccountInfoDTO;
//import com.yunxin.core.application.service.MerchantQueryAdminService;
//import com.yunxin.core.application.service.TeamService;
//import com.yunxin.core.domain.model.team.Team;
//import com.yunxin.core.utils.infra.utils.AesUtils;
//import io.swagger.v3.oas.annotations.Operation;
//import io.swagger.v3.oas.annotations.Parameter;
//import io.swagger.v3.oas.annotations.security.SecurityRequirement;
//import io.swagger.v3.oas.annotations.tags.Tag;
//import jakarta.validation.Valid;
//import lombok.RequiredArgsConstructor;
//import org.apache.commons.lang3.ObjectUtils;
//import org.springdoc.core.annotations.ParameterObject;
//import org.springframework.security.access.prepost.PreAuthorize;
//import org.springframework.validation.annotation.Validated;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.List;
//import java.util.Map;
//
///**
// * 商户用户控制器
// *
// * @author zero°
// * @since 2023-06-01
// */
//@Tag(name = "021.商户用户接口")
//@RestController
//@RequestMapping("/api/v1/user/merchant")
//@RequiredArgsConstructor
//public class SysUserMerchantController {
//
//    private final UserApplicationService userService;
//
//    private final UserQueryService userQueryService;
//
//    private final MerchantQueryAdminService merchantQueryAdminService;
//
//    private final TeamService teamService;
//
//    private final UserMerchantRepository userMerchantRepository;
//
//    @Operation(summary = "商户用户分页列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @GetMapping("/page")
//    public PageResult<UserMerchantInfoResult> getUserPage(@ParameterObject UserMerchantPageCommand command) {
//        Long userId = SecurityUtils.X.getUser().getUserId();
//        if (!SecurityUtils.X.isBokeMerchantUser()&&!SecurityUtils.X.isBokeTeamUser()){
//            throw new BusinessException("权限不够");
//        }
//        if(ObjectUtils.isEmpty(command.getTeamIds())) {
//            if (SecurityUtils.X.isBokeMerchantUser()){
//                //商户管理员只能看自己所有团队下的账户信息
//                Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
//                List<Team> teams = teamService.getTeamList(merchantId);
//                if (CollUtil.isEmpty(teams)){
//                    return PageResult.success(Collections.emptyList(),0);
//                }
//                List<Long> teamIds = teams.stream().map(i -> i.getId().longValue()).toList();
//                command.setTeamIds(teamIds);
//            }else if (SecurityUtils.X.isBokeTeamUser()) {
//                //团队管理员只能看自己团队下的账户信息
//                List<Team> teams = teamService.getTeamListByUserId(userId);
//                if (CollUtil.isEmpty(teams)){
//                    return PageResult.success(Collections.emptyList(),0);
//                }
//                List<Long> teamIds = teams.stream().map(i -> i.getId().longValue()).toList();
//                command.setTeamIds(teamIds);
//            }
//        }
//        Page<UserMerchantInfoResult> pageResult = userQueryService.getUserMerchantPage(command);
//        return PageResult.success(pageResult.getRecords(), pageResult.getTotal());
//    }
//
//    @Operation(summary = "一键修改商户用户状态", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @GetMapping(value = "/updateStatus")
//    @PreAuthorize("@ss.hasPerm('sys:user:merchant:update:status')")
//    @Resubmit
//    @AutoLog(value = "一键修改商户用户状态")
//    public Result updateUserStatus() {
//        //只允许波克商户管理员操作
//        if (!SecurityUtils.X.isBokeMerchantUser()) return Result.failed(AdminResultCode.USER_MERCHANT_ROLE_ERROR);
//        Long userId = SecurityUtils.X.getUser().getUserId();
//
//        List<Long> merchantIds = userQueryService.getUserMerchantIds(userId);
//        Long merchantId;
//        if (CollUtil.isNotEmpty(merchantIds)) {
//            merchantId = merchantIds.get(0);
//        } else {
//            merchantId = 0L;
//        }
//        //查询当前商户下的用户集合(只查询开启状态)
//        List<Long> userIds = userQueryService.getMerchantUserIds(userId);
//        if (CollUtil.isEmpty(userIds)) return Result.failed("未查询到该用户商户信息！");
//        //修改当前商户下用户接单状态 0:关闭， 1：开启
//        userIds.stream().forEach(user -> userService.updateUserMerchantReceivingStatus(user, 0,merchantId));
//        return Result.success();
//    }
//
//    @Operation(summary = "新增商户用户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping
//    @PreAuthorize("@ss.hasPerm('sys:user:merchant:add')")
//    @Resubmit
//    @AutoLog(value = "新增商户用户")
//    public Result<Boolean> saveUser(@RequestBody @Valid AddUserMerchantCommand command) {
//        checkRole();
//        boolean result = userService.saveMerchantUser(command);
//        return Result.judge(result);
//    }
//
//    @Operation(summary = "商户用户表单数据", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @GetMapping("/{userId}/form")
//    public Result<UserDetailDTO> getUserFormResponse(@Parameter(description = "用户ID") @PathVariable Long userId) {
//        UserDetailDTO userDetailDTO = userQueryService.getUserInfoById(userId);
//        return Result.success(userDetailDTO);
//    }
//
//    @Operation(summary = "修改商户用户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PutMapping(value = "/{userId}")
//    @PreAuthorize("@ss.hasPerm('sys:user:merchant:edit')")
//    @Resubmit
//    @AutoLog(value = "修改商户用户")
//    public Result<Boolean> updateUser(@Parameter(description = "用户ID") @PathVariable Long userId,
//            @RequestBody @Validated UpdateUserMerchantCommand command) {
//        checkRole();
//        checkUserMerchant(SecurityUtils.X.getUser().getUserId(), userId);
//        List<Long> merchantIds = userQueryService.getUserMerchantIds(userId);
//        if (merchantIds.isEmpty()) {
//            throw new BusinessException(AdminResultCode.USER_MERCHANT_ERROR);
//        }
//        boolean result = userService.updateMerchantUser(command);
//        return Result.judge(result);
//    }
//
//    @Operation(summary = "获取自己个人信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @GetMapping(value = "/getOwnUser")
//    @AutoLog(value = "获取自己个人信息")
//    public Result<UserDetailDTO> getOwnUser() {
//        UserDetailDTO userDetailDTO = userQueryService.getUserInfoById(SecurityUtils.X.getUserId());
//        return Result.success(userDetailDTO);
//    }
//
//    @Operation(summary = "修改自己个人信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping(value = "/updateOwnUser")
//    @AutoLog(value = "修改自己个人信息")
//    public Result<Boolean> updateOwnUser(@RequestBody @Validated UpdateUserDetailDTO userDetailDTO) {
//        userDetailDTO.setId(SecurityUtils.X.getUserId());
//        boolean b = userService.updateOwnUser(userDetailDTO);
//        return Result.judge(b);
//    }
//
//    @Operation(summary = "修改自己个人密码", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping(value = "/updateOwnUserPassword")
//    @AutoLog(value = "修改自己个人信息")
//    public Result<Boolean> updateOwnUserPassword(@RequestParam String password) {
//        boolean result = userService.updatePassword(SecurityUtils.X.getUserId(), password);
//        return Result.judge(result);
//    }
//
//    @Operation(summary = "修改商户用户密码", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PatchMapping(value = "/{userId}/password")
//    @PreAuthorize("@ss.hasPerm('sys:user:merchant:reset_pwd')")
//    public Result<Boolean> updatePassword(@Parameter(description = "用户ID") @PathVariable Long userId,
//                                          @RequestParam String password) {
//        boolean result = userService.updatePassword(userId, password);
//        return Result.judge(result);
//    }
//
//    @Operation(summary = "修改商户用户状态", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PatchMapping(value = "/{userId}/status")
//    @PreAuthorize("@ss.hasPerm('sys:user:merchant_status:edit')")
//    @AutoLog(value = "修改商户用户状态")
//    public Result<Boolean> updateUserStatus(@Parameter(description = "用户ID") @PathVariable Long userId,
//            @Parameter(description = "用户状态(1:启用;0:禁用)") @RequestParam Integer status) {
//        checkRole();
//        checkUserMerchant(SecurityUtils.X.getUser().getUserId(), userId);
//        boolean result = userService.updateUserMerchantStatus(userId, status);
//        return Result.judge(result);
//    }
//
//    @Operation(summary = "修改商户用户账号接单状态", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PatchMapping(value = "/{userId}/receiving/status")
//    @PreAuthorize("@ss.hasPerm('sys:user:merchant_receiving_status:edit')")
//    @AutoLog(value = "修改商户用户账号接单状态")
//    public Result<Boolean> updateUserMerchantReceivingStatus(@Parameter(description = "用户ID") @PathVariable Long userId,
//                                            @Parameter(description = "接单状态 0.关闭 1.开启") @RequestParam Integer receivingStatus) {
//        checkRole();
//        checkUserMerchant(SecurityUtils.X.getUser().getUserId(), userId);
//        List<Long> merchantIds = userQueryService.getUserMerchantIds(SecurityUtils.X.getUser().getUserId());
//        Long merchantId = 0L;
//        if (CollUtil.isNotEmpty(merchantIds)) {
//            merchantId = merchantIds.get(0);
//        }
//        boolean result = userService.updateUserMerchantReceivingStatus(userId, receivingStatus,merchantId);
//        return Result.judge(result);
//    }
//
//    @Operation(summary = "获取商户用户账号下拉列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @GetMapping(value = "/listMerchantUserAccount")
//    public Result<List<AdminMerchantUserAccountInfoDTO>> listMerchantUserAccount() {
//        Long userId = SecurityUtils.X.getUser().getUserId();
//        if (!SecurityUtils.X.isBokeMerchantUser()&&!SecurityUtils.X.isBokeTeamUser()){
//            throw new BusinessException("权限不够");
//        }
//        if (SecurityUtils.X.isBokeMerchantUser()){
//            //商户管理员只能看自己所有团队下的账户信息
//            Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
//            List<Team> teams = teamService.getTeamList(merchantId);
//            if (CollUtil.isEmpty(teams)){
//                return Result.success(null);
//            }
//            List<Long> teamIds = teams.stream().map(i -> i.getId().longValue()).toList();
//            List<MerchantUserAccountInfoDTO> list = teamService.getUserForTeamList(null,teamIds);
//            List<AdminMerchantUserAccountInfoDTO> dtoList = list.stream().map(x -> {
//                AdminMerchantUserAccountInfoDTO dto = new AdminMerchantUserAccountInfoDTO();
//                dto.setId(x.getId());
//                dto.setAccountName(AesUtils.X.decrypt(x.getAccountName(),null));
//                return dto;
//            }).toList();
//            return Result.success(dtoList);
//        }else if (SecurityUtils.X.isBokeTeamUser()) {
//            //团队管理员只能看自己团队下的子账户
//            List<MerchantUserAccountInfoDTO> list = teamService.getUserForTeamList(userId,null);
//            List<AdminMerchantUserAccountInfoDTO> dtoList = list.stream().map(x -> {
//                AdminMerchantUserAccountInfoDTO dto = new AdminMerchantUserAccountInfoDTO();
//                dto.setId(x.getId());
//                dto.setAccountName(AesUtils.X.decrypt(x.getAccountName(),null));
//                return dto;
//            }).toList();
//            return Result.success(dtoList);
//        }
//        //商户管理员只能看自己商户下的子账户
//        boolean result = SecurityUtils.X.isBokeMerchantUser();
//        if (!result) {
//            return Result.success(CollUtil.newArrayList());
//        }
//        List<Long> merchantIds = userQueryService.getUserMerchantIds(SecurityUtils.X.getUser().getUserId());
//        List<MerchantUserAccountInfoDTO> list = merchantQueryAdminService.listMerchantUserAccountByMerchantId(merchantIds.get(0));
//        List<AdminMerchantUserAccountInfoDTO> dtoList = list.stream().map(x -> {
//            AdminMerchantUserAccountInfoDTO dto = new AdminMerchantUserAccountInfoDTO();
//            dto.setId(x.getId());
//            dto.setAccountName(x.getAccountName());
//            return dto;
//        }).toList();
//        return Result.success(dtoList);
//    }
//
//    /**
//     * 判断登录用户与用户（被操作用户）是否同一商户
//     * @param loginUserId loginUserId
//     * @param userId userId
//     */
//    private void checkUserMerchant(Long loginUserId, Long userId){
//        List<Long> merchantIds = userQueryService.getUserMerchantIds(loginUserId);
//        List<Long> userMerchantIds = userQueryService.getUserMerchantIds(userId);
//        if (!merchantIds.get(0).equals(userMerchantIds.get(0))) {
//            throw new BusinessException(AdminResultCode.USER_MERCHANT_ERROR);
//        }
//    }
//
//    /**
//     * 判断登录用户权限，必须是商户管理员角色或者团队管理员角色才允许操作
//     */
//    private void checkRole(){
//        if (SecurityUtils.X.getRoles().size() != 1) {
//            throw new BusinessException(AdminResultCode.USER_MERCHANT_ROLE_ERROR);
//        }
//        if (!SecurityUtils.X.isBokeMerchantUser() && !SecurityUtils.X.isBokeTeamUser()) {
//            throw new BusinessException(AdminResultCode.ADMIN_MERCHANT_ROLE_ERROR);
//        }
//    }
//
//
////    @Operation(summary = "新增子账户所属角色", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
////    @GetMapping("/roleList")
////    public Result<List<Map>> abutmentType() {
////        Long userId = SecurityUtils.X.getUser().getUserId();
////        //查询该用户角色
////        SysRoleDO sysRoleDO = userQueryService.getUserRoleId(userId);
////        //团队管理员不能分配角色
////        if (ObjUtil.equals(sysRoleDO.getCode(), SystemConstants.BOKE_TEAM_USER)) return Result.success();
////        List<Map> result = new ArrayList<>();
////        result.add(Map.of("role","业务员","id",13));
////        result.add(Map.of("role","话务员","id",14));
////        result.add(Map.of("role","团队管理员","id",12));
////        return Result.success(result);
////    }
//}
